<template>
  <div v-if="isOpen" class="com-page">
    <component :is="ContentComponent" :params="params" :dialog="dialog" @load="onLoad" @success="onSuccess" ref="content"></component>
  </div>
</template>

<script setup>
import {loadComponent} from 'framework'
import {ref, defineAsyncComponent, useSlots,watch} from 'vue'

// const hasHeaderSlot = !!useSlots().header
// const hasFooterSlot = !!useSlots().footer
import {useRoute,useRouter} from 'vue-router'


const route=useRoute()

const router=useRouter()


const params = ref(null)

const {href, closeOnMask,pages} = defineProps({
  href: String,
  closeOnMask: {
    value: false,
    type: Boolean
  },
  pages:Object
})

const ContentComponent = defineAsyncComponent(() => loadComponent(href))

const componentMap={}
const currentPage=ref()

if(pages){
  for(let k of Object.keys(pages)){
    componentMap[k]=defineAsyncComponent(() => loadComponent(pages[k]))
  }
}


const content = ref(null)
const isOpen = ref(false)
const loading = ref(false)
let submitListener=()=>{}
const emit=defineEmits()
const dialog={
  loading(v){
    loading.value=v
  },
  onSubmit(cb){
    submitListener=cb
  },
  success(data){
    //isOpen.value=false
    cancel()
    _resolve(data)
  },
  emit(e,data){
    emit(e,data)
  },
  cancel(){
    cancel()
  },
  submit(){
    return submit()
  }
}
//let _resolve;
let _resolves=[]
function _resolve(data){
  let rses=_resolves;
  _resolves=[];
  for(let rs of rses){
    rs(data)
  }

}
let canBack=false
function open(_params) {
  isOpen.value = true
  canBack=true
  if(!_params||Object.keys(_params).length==0){
    router.push({query:{_:''}})
  }else{
    router.push({query:_params})
  }

  params.value = _params
  //console.log(content.value)
  return new Promise((resolve) => {
    //_resolve=resolve
    _resolves.push(resolve)
  })
}
const setParams=(v)=>{
  if(v&&Object.keys(v).length>0){
    params.value=v
    isOpen.value = true
  }else{
    isOpen.value = false
    params.value={}
  }
}

watch(()=>route.query,setParams)
setParams(route.query)




function cancel() {
  if(canBack){
    canBack=false
    router.go(-1)
  }else{
    router.replace({query:{}})
  }
  isOpen.value = false
}
function onSuccess(data){
  isOpen.value=false
  _resolve(data)
}
function submit() {
  return new Promise(resolve=>{
    _resolves.push(resolve)
    submitListener()
    if(content.value.submit){
      content.value.submit(loading,onSuccess)
    }
  })
}

function onLoad(v){
  loading.value=v
}
defineExpose({open, cancel, loading, submit,ref:content})
</script>
<style>
.com-page{
  position: absolute;
  top:0;
  left:0;
  width: 100%;
  height: 100%;
  z-index: 2;
  padding: 16px 24px;
  background-color: #F7F8FA;
}
</style>
